import { omit } from "lodash"
import { appLocalStorage } from "./tools"

/**
 * 应用请求
 * @param input 请求信息
 * @param init 请求初始化
 * @returns data
 */
export const appFetch = async <R = any>(input: RequestInfo | URL, init?: RequestInit): Promise<R> => {
  try {
    const token = appLocalStorage.getValue('token')
    const res = await fetch(
      input,
      {
        mode: 'cors',
        headers: {
          "Content-Type": 'application/json',
          "Authorization": `Bearer ${token}`,
          ...init?.headers
        },
        ...omit(init, 'headers')
      }
    )
    const data = await res.json()
    if (data.success) {
      return data
    } else {
      throw data
    }
  } catch (error) {
    throw error
  }
}